package handler

import (
	"github.com/sirupsen/logrus"
	"gofile/src/config"
	"gofile/src/util"
	"io"
	"net/http"
	"os"
	"path/filepath"
)

func UploadHandler(w http.ResponseWriter, r *http.Request) {
	//1G
	var maxUploadSize int64 = 1024 * 1024 * 1024 * 1
	r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
	if err := r.ParseMultipartForm(maxUploadSize); err != nil {
		util.ProcessResult("文件超过1G", err, w)
		return
	}
	fileName := r.FormValue("name")
	filePath := r.FormValue("path")
	file, _, err := r.FormFile("file")

	logrus.Infof("开始上传文件:%s到目录:%s", fileName, filePath)
	if err != nil {
		util.ProcessResult("获取表单中文件(file)失败", err, w)
		return
	}
	defer file.Close()

	fileBytes, err := io.ReadAll(file)

	fileType := http.DetectContentType(fileBytes)
	myCfg := config.GetConfig()
	newPath := filepath.Join(myCfg.File.Dir+filePath, fileName)

	logrus.Infof("上传文件:%s，文件类型:%s", newPath, fileType)

	newFile, err := os.Create(newPath)
	if err != nil {
		util.ProcessResult("创建文件"+newPath+"失败", err, w)
		return
	}
	defer newFile.Close()
	if _, err := newFile.Write(fileBytes); err != nil {
		util.ProcessResult("写文件"+newPath+"失败", err, w)
		return
	}
	util.ProcessResult("success", err, w)
	logrus.Infof("上传文件:%s到目录:%s成功", fileName, filePath)
}
